package com.fhz.kotlinstest.truepaging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fhz.kotlinstest.Banner
import com.fhz.kotlinstest.Data
import com.fhz.kotlinstest.UserRemoteDataSource

class ClassifyNetPagingSource(
    private val appStoreRepository: UserRemoteDataSource,
) : PagingSource<Int, Data>() {

    override fun getRefreshKey(state: PagingState<Int, Data>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Data> {
        return try {
            val page = params.key ?: 1  //当前页码，若为空则设为1
            val limit = params.loadSize  //每次加载的数目
//            val response = appStoreRepository.getBanner((page - 1) * limit, limit)  //网络请求数据
            val response = appStoreRepository.getBanner(1, 1)  //网络请求数据
            val prevKey = if (page > 1) page - 1 else null   //计算上一页的页码
            val nextKey = page + 1 //计算下一页的页码
            val responseData =  response.data   //获取请求返回的数据
            //将数据和页码设置到LoadResult中
            LoadResult.Page(
                data = responseData,
                prevKey = prevKey,
                nextKey = nextKey
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}